import Vue from 'vue'
import Router from 'vue-router'
import index from '@/components/index/index'
import chooseCarsType from '@/components/home/chooseCarsType/chooseCarsType'
import login from '@/components/login/login'
import user from '@/components/user/user'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/index',
      name: 'index',
      component: index
    },
    {
    	path: '/chooseCarsType',
      name: 'chooseCarsType',
      component: chooseCarsType
    },
    {
    	path: '/login',
      name: 'login',
      component: login
    },
    {
      path: '/user',
      name: 'user',
      meta: {
      	requireAuth: true //进入该路由要登录
      },
      component: user,
      beforeEnter: (to, from, next) => {
				if(to.meta.requireAuth){//判断路由是否需要登录
					if(window.localStorage.getItem('token')){//通过vue的state获取当前的token是否存在
						next();
					}else {
						next({
							path: '/login',
							query: {redirect: to.fullPath}//将跳转的路由path作为参数，登录成功后跳转到该路由
						})
					}
				}
				else{
					next();
				}
			}
    },
    {
    	path: '/', 
    	redirect: '/index'
    },
  ]
})
